home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 5213 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.1 KB

  1. Path: crl.crl.com!not-for-mail
  2. From: bobfry@crl.com (Robert Fry)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Character String --> Integer
  5. Date: 8 Feb 1996 10:49:40 -0800
  6. Organization: CRL Dialup Internet Access
  7. Message-ID: <4fdgk4$m2@crl.crl.com>
  8. References: <4fb0ga$lsa@remus.rutgers.edu>
  9. NNTP-Posting-Host: crl.com
  10.  
  11. wempa@remus.rutgers.edu (Force Of Nature) writes:
  12.  
  13. >Is there an easy way to convert a character string such as '2425' to the
  14. >integer 2425 ???  The only way I can think of is to pick off characters 
  15. >one at a time and use switch statements to determine the value (0-9) and
  16. >then multiply by the correct power of 10.  Is there an easier way to do
  17. >this ???????
  18.  
  19. This question should really be in the FAQ since it's a rather common one. 
  20. But I can think of three methods that are used fairly often:
  21.  
  22.  sscanf()
  23.  atoi()
  24.  for(result=0,ptr=string;*ptr;*ptr++)result=10*result+*ptr-'0';
  25.  
  26. (Note that the last hasn't been checked and doesn't handle errors (such 
  27. as overflow or non-digits) and no doubt has several other problems with 
  28. it -- but should illustrate a more compact method than switch().)
  29.   Bob
  30.